package com.sky.service.impl;

import cn.hutool.http.server.HttpServerResponse;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */

    @Override
    public TurnoverReportVO getSumAmount(LocalDate begin, LocalDate end) {
        //首先获得日期的list
        ArrayList<LocalDate> dateList = getDateList(begin, end);
        //获得营业额的集合
        ArrayList<BigDecimal> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            BigDecimal amount = orderMapper.getSumAmount(map);
            amount = amount == null ? BigDecimal.valueOf(0.0) : amount;
            turnoverList.add(amount);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getSumUser(LocalDate begin, LocalDate end) {

        //首先获得日期的list
        ArrayList<LocalDate> dateList = getDateList(begin, end);

        //获取新增员工的数量
        //select count(id) from user where create_time > ? and create_time < ?
        ArrayList<Integer> newUserList = new ArrayList<>();

        //获取总员工的数量
        //select count(id) from user where  create_time < ?
        ArrayList<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map newUserMap = new HashMap<>();
            newUserMap.put("beginTime", beginTime);
            newUserMap.put("endTime", endTime);
            Map totalUserMap = new HashMap<>();
            totalUserMap.put("endTime", endTime);
            Integer newUserCount = userMapper.getUserCount(newUserMap);
            newUserList.add(newUserCount);
            Integer totalUserCount = userMapper.getUserCount(totalUserMap);
            totalUserList.add(totalUserCount);

        }


        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //首先获得日期的list
        ArrayList<LocalDate> dateList = getDateList(begin, end);

        //每日订单数
        //select count(*) from order where create_time > ? and create_time < ?
        ArrayList<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数
        //select count(*) from order where create_time > ? and create_time < ? and status = 5
        ArrayList<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Integer orderCount = orderMapper.getCount(map);
            orderCountList.add(orderCount);
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getCount(map);
            validOrderCountList.add(validOrderCount);
        }

//        Map map = new HashMap();
        //订单总数
        //select count(id) from order
//        Integer totalOrderCount = new Integer(0);
//        Integer totalOrderCount =  orderMapper.getCount(map);

        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();


        //有效订单数
        //select count(id) from order where status = 5
//        map.put("status", Orders.COMPLETED);
//        Integer validOrderCount = new Integer(0);
//        Integer validOrderCount =  orderMapper.getCount(map);
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
//        Double orderCompletionRate =  ((double) validOrderCount / (double) totalOrderCount);
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 获取日期的集合
     *
     * @param begin
     * @param end
     * @return
     */
    private static ArrayList<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 查询销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        ArrayList<String> nameList = new ArrayList<>();
        ArrayList<BigDecimal> numberList = new ArrayList<>();

        Map map = new HashMap();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", Orders.COMPLETED);

        List<Map<String, Object>> list = orderMapper.getTop10(map);
        for (Map<String, Object> map2 : list) {
            String name = (String) map2.get("name");
            nameList.add(name);
            BigDecimal sum = (BigDecimal) map2.get("sum");
            numberList.add(sum);

        }


        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出Excel报表接口
     *
     * @param httpServletResponse
     */
    @Override
    public void export(HttpServletResponse httpServletResponse) {
        //构造时间
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateEnd, LocalTime.MAX);

        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheetAt(0);
            //书写时间
            sheet.getRow(1).getCell(1).setCellValue(dateBegin + "至" + dateEnd);

            //书写其他数据
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //书写明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO businessDataPerDay = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //获取每一行
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataPerDay.getTurnover());
                row.getCell(3).setCellValue(businessDataPerDay.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataPerDay.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataPerDay.getUnitPrice());
                row.getCell(6).setCellValue(businessDataPerDay.getNewUsers());
            }


            //输出资源到浏览器下载
            ServletOutputStream out = httpServletResponse.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }





    }
}
